#include "main/utils.h"
#include "lib/list.h"
using namespace std;

ListNode* reverseList(ListNode* head) {
  ListNode* pre_node = nullptr;
  ListNode* cur_node = head;
  ListNode* tail_node = head;
  while (cur_node) {
    ListNode* next_node = cur_node->next;
    if (!next_node) {
      tail_node = cur_node;
    }
    cur_node->next = pre_node;
    pre_node = cur_node;
    cur_node = next_node;
  }
  return tail_node;
}

ListNode* sum(ListNode* head1, ListNode* head2) {
  auto reverse_head1 = reverseList(head1);
  auto reverse_head2 = reverseList(head2);
  int carry = 0;
  ListNode* reverse_sum_head = nullptr;
  ListNode* cur_reverse_sum = nullptr;
  while (reverse_head1 || reverse_head2) {
    int value1 = reverse_head1 ? reverse_head1->value : 0;
    int value2 = reverse_head2 ? reverse_head2->value : 0;
    int cur_sum = value1 + value2 + carry;
    if (cur_sum >= 10) {
      cur_sum -= 10;
      carry = 1;
    } else {
      carry = 0;
    }
    ListNode* cur_node = new ListNode();
    cur_node->value = cur_sum;
    cur_node->next = nullptr;
    if (cur_reverse_sum) {
      cur_reverse_sum->next = cur_node;
      cur_reverse_sum = cur_reverse_sum->next;
    } else {
      reverse_sum_head = cur_node;
      cur_reverse_sum = cur_node;
    }
    reverse_head1 = reverse_head1 ? reverse_head1->next : nullptr;
    reverse_head2 = reverse_head2 ? reverse_head2->next : nullptr;
  }
  if (carry > 0) {
    ListNode* cur_node = new ListNode();
    cur_node->value = carry;
    cur_reverse_sum->next = cur_node;
  }
  return reverseList(reverse_sum_head);
}

int main() {
  vector<int> vec1 = {9, 9, 2, 3};
  ListNode* phead1 = CreateList(vec1);

  vector<int> vec2 = {5, 3, 1};
  ListNode* phead2 = CreateList(vec2);

  ListNode* ret = sum(phead1, phead2);
  PrintList(ret);

  return 0;
}
